package com.bwie.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.PageUserVo;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhaijiaqi
 * @Date: 2025/5/21 15:24
 * @Description:
 **/
@RestController
@RequestMapping("/user/index")
@Slf4j
public class IndexContoller {
    @Autowired
    TbUserService tbUserService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    FastFileStorageClient fastFileStorageClient;

    /**
     * 登录接口
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Validated   LoginVo loginVo, BindingResult result){
        if(result.hasFieldErrors()){
            return Result.error().setMsg(result.getFieldError().getDefaultMessage());
        }
        TbUser user = tbUserService.getOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if(user==null){
            return Result.error().setCode(500).setMsg("用户不存在");
        }
        String md5pass = DigestUtil.md5Hex(loginVo.getUserPass());
        log.info("用户密码"+md5pass);
        if(!user.getUserPass().equals(md5pass)){
            return Result.error().setCode(500).setMsg("用户密码不正确");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .claim("userName", user.getUserName())
                .claim("userNick", user.getNickName())
                .compact();

        redisTemplate.opsForValue().set("token-"+user.getUserId(),token,15, TimeUnit.MINUTES);
        user.setToken(token);
        user.setUserPass(null);
        return Result.ok().setData(user);
    }

    /**
     * 获取用户权限
     * @return
     */
    @PostMapping("/getMenuTree")
    public Result getMenuTree(HttpServletRequest request){
        //--获取token 用户管理员ID
        //获取管理员权限生成树形菜单
        String token = request.getHeader("token");
        if(token==null){
            return Result.error().setData(500).setMsg("请登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
       List<TbMenu> tbMenus= tbUserService.geteMenuTree(userId);
      return Result.ok().setData(tbMenus);

    }

    /**
     * 用户列表
     * @return
     */
    @PostMapping("/UserList")
    public Result UserList(@RequestBody PageUserVo pageUserVo){

       return tbUserService.UserList(pageUserVo);
    }

    /**
     * 用户修改
     * @return
     */
    @PostMapping("/UpdataUser")
    public Result UpdataUser(@RequestBody TbUser tbUser){
        return  tbUserService.UpdataUser(tbUser);
    }

    /**
     * 上传图片
     */
    @PostMapping("/UpimageFile")
    public Result UpimageFile(@RequestPart("file")MultipartFile file){
        return tbUserService.UpimageFile(file);
    }

    /**
     * 批量删除
     * @return
     */
    @PostMapping("/deleteUserById/{userId}")
    public Result deleteUserById(@PathVariable("userId") Integer userId){
        return tbUserService.deleteUserById(userId);
    }

    /**
     * 批量删除商户
     * @param userList
     * @return
     */
    @PostMapping("/deleteUserAll")
    public Result deleteUserAll(@RequestBody List<TbUser> userList){
        return tbUserService.deleteUserAll(userList);
    }

    /**
     * 修改状态
     * @param tbUser
     * @return
     */
    @PostMapping("/CheckUserUpdata")
    public Result CheckUserUpdata(@RequestBody TbUser tbUser){
        return tbUserService.CheckUserUpdata(tbUser);
    }
}
